package edu.zjut.hjg.saas.biz.service.impl;

import static edu.zjut.hjg.saas.biz.support.AppConstants.IMAGE_RELATIVE_PATH;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.transaction.annotation.Transactional;

import edu.zjut.hjg.saas.biz.dao.ActivityDao;
import edu.zjut.hjg.saas.biz.dao.AlbumDao;
import edu.zjut.hjg.saas.biz.dao.UserLogDao;
import edu.zjut.hjg.saas.biz.model.Activity;
import edu.zjut.hjg.saas.biz.model.Album;
import edu.zjut.hjg.saas.biz.model.UserLog;
import edu.zjut.hjg.saas.biz.service.ActivityService;
import edu.zjut.hjg.saas.biz.support.AlbumType;
import edu.zjut.hjg.saas.biz.support.OperateType;
import edu.zjut.hjg.saas.biz.support.Paginated;

public class ActivityServiceImpl implements ActivityService {

    private ActivityDao activityDao;
    private UserLogDao  userLogDao;
    private AlbumDao    albumDao;
    private String      baseFilePath;
    private Random      random = new Random();

    public void setActivityDao(ActivityDao activityDao) {
        this.activityDao = activityDao;
    }

    public void setUserLogDao(UserLogDao userLogDao) {
        this.userLogDao = userLogDao;
    }

    public void setAlbumDao(AlbumDao albumDao) {
        this.albumDao = albumDao;
    }

    public void setBaseFilePath(String baseFilePath) {
        this.baseFilePath = baseFilePath;
    }

    @Override
    public File create(Activity activity, String oldFileName, String operator) {
        if (activity.getAlbum().getId().intValue() == -1) {
            // 没有相册，创建默认相册
            Album album = new Album();
            album.setAlbumType(AlbumType.ACTIVITY);
            album.setKindergarten(activity.getKindergarten());
            album.setName("默认相册");
            albumDao.create(album);
            activity.setAlbum(album);
        }
        String picturePath = generatePicturePath(activity, oldFileName);
        activity.setPicturePath(picturePath);
        activityDao.create(activity);
        File file = new File(baseFilePath + activity.getPicturePath());
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        UserLog userLog = new UserLog();
        userLog.setKindergarten(activity.getKindergarten());
        userLog.setLoginId(operator);
        userLog.setOperateType(OperateType.INSERT);
        userLog.setDescription("上传了一张幼儿园活动相片");
        userLogDao.create(userLog);
        return file;
    }

    @Override
    @Transactional
    public void deleteByIdAndAppId(int id, int appId, String operator) {
        Activity activity = activityDao.findByIdAndAppId(id, appId);
        if (activity == null) {
            throw new RuntimeException("no activity found for id=" + id + " and appId=" + appId);
        }
        File file = new File(baseFilePath + activity.getPicturePath());
        // 删除图片文件
        file.delete();
        activityDao.deleteByIdAndAppId(id, appId);
        UserLog userLog = new UserLog();
        userLog.getKindergarten().setId(appId);
        userLog.setLoginId(operator);
        userLog.setOperateType(OperateType.DELETE);
        userLog.setDescription("删除了一张幼儿园活动相片");
        userLogDao.create(userLog);
    }

    @Override
    public Activity findById(int id) {
        return activityDao.load(id);
    }

    @Override
    public Activity findByIdAndAppId(int id, int appId) {
        Activity activity = activityDao.findByIdAndAppId(id, appId);
        if (activity == null) {
            throw new RuntimeException("no activity found for id=" + id + " and appId=" + appId);
        }
        return activity;
    }

    @Override
    public Paginated<Activity> listByAlbumIdAndAppId(int albumId, int appId, int pageSize, int page) {
        return activityDao.listByAlbumIdAndAppId(albumId, appId, pageSize, page);
    }

    private String generatePicturePath(Activity activity, String oldFileName) {
        // 3位随机数
        String rand = (random.nextInt(900) + 100) + "";
        String suffix = oldFileName.substring(oldFileName.lastIndexOf('.'));
        String fileName = System.currentTimeMillis() + rand + suffix;
        return IMAGE_RELATIVE_PATH + "/" + activity.getKindergarten().getId() + "/"
                + activity.getAlbum().getId() + "/" + fileName;
    }

    @Override
    public Map<Integer, String> getAlbumCoversByAlbumIds(List<Integer> albumIds) {
        Map<Integer, String> covers = new HashMap<Integer, String>();
        if (albumIds.isEmpty()) {
            return covers;
        }
        List<Activity> activities = activityDao.listFirstsGroupByAlbumIds(albumIds);
        for (Activity activity : activities) {
            covers.put(activity.getAlbum().getId(), activity.getPicturePath());
        }
        return covers;
    }

    @Override
    public Map<Integer, String> getAlbumCoversByAlbums(List<Album> albums) {
        List<Integer> albumIds = new ArrayList<Integer>(albums.size());
        for (Album album : albums) {
            albumIds.add(album.getId());
        }
        return this.getAlbumCoversByAlbumIds(albumIds);
    }

    @Override
    public List<Activity> listByLimitAndAppId(int limit, int appId) {
        return activityDao.listByLimitAndAppId(limit, appId);
    }

    @Override
    public List<Activity> listByLimit(int limit) {
        return activityDao.listByLimit(limit);
    }

    @Override
    public Paginated<Activity> listAll(int pageSize, int page) {
        return activityDao.listAll(pageSize, page);
    }
}
